<?php
namespace Utuo;

class TabTree {
	
	private $icos = array('&nbsp;&nbsp;&nbsp;&nbsp;└─', '&nbsp;&nbsp;&nbsp;&nbsp;├─', '&nbsp;&nbsp;&nbsp;&nbsp;│', '&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;');
	
	public static function newInstance() {
		static $tabTree = null;
		if($tabTree) return $tabTree; 
		else{
			$tabTree = new TabTree();
			return $tabTree;
		}
	}
	
	/**
	 * list转树型结构
	 * @param array $list 查询出的二维数组
	 * @param string $pk 主键名
	 * @param string $pid 父键名
	 * @param string $child 
	 * @param number $root
	 * @param unknown $current_root
	 */
	public function listToTree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0, &$current_root = array()) {
		$child_list = array();
		foreach($list as $k => &$data){
			if($data[$pid] == $root && !$data['is_deleted']){
				$child_list[] = &$data;
			}
		}
	
		if(!empty($child_list)) {
			$lastNode = $child_list[count($child_list)-1];
			$current_root[$child] = &$child_list;
			foreach($child_list as $k => &$data) {
				if($lastNode[$pk] == $data[$pk]){
					$data['last'] = 1;
					$data['last_path'] = $current_root['last_path'].',1';
				}else{
					$data['last_path'] = $current_root['last_path'].',0';
				}
				/*获得图标*/
				$tab = "";
				if($data[$pid] == '0'){ // 是否为根
				} else {
					if($data['last']){
						$tab = $this->getTab($data['last_path']).$this->icos[0]."&nbsp;&nbsp;";
					} else {
						$tab = $this->getTab($data['last_path']).$this->icos[1]."&nbsp;&nbsp;";
					}
				}
				$data['tab'] = $tab;
				$this->listToTree($list, $pk, $pid, $child, $data[$pk], $data);
			}
		}
	}
	
	// 获得tab
	private function getTab($path) {
		$tab = "";
		$arr = explode(',', trim($path, ','));
		array_pop($arr);
		array_shift($arr);
		foreach($arr as $v){
			if(!($v*1)){
				$tab.=$this->icos[2];
			}else{
				$tab.=$this->icos[3];
			}
		}
		return $tab;
	}
	
	
	/**
	 * 将listToTree的树还原成列表
	 * @param  array $tree  原来的树
	 * @param  string $child 孩子节点的键
	 * @param  string $order 排序显示的键，一般是主键 升序排列
	 * @param  array  $list  过渡用的中间数组，
	 * @return array        返回排过序的列表数组
	 */
	public function treeToList($tree, $child = '_child', $order='id', &$list = array()) {
		if(is_array($tree)) {
			$refer = array();
			foreach ($tree as $key => $value) {
				$reffer = $value;
				if($has_child = isset($reffer[$child])) unset($reffer[$child]);
				$list[] = $reffer;
				if($has_child) {
					$this->treeToList($value[$child], $child, $order, $list);
				}
			}
		}
		return $list;
	}
	
}